package com.example.gkcircle.library.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.example.gkcircle.R;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.ThreadPoolUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.media.ThumbnailUtils;
import android.util.Log;

/**
 * 
 * @ClassName: AutoGetCaptcha
 * @Description: TODO(自动识别验证码)
 * @author ZhouHua
 * @date 2015年7月25日 下午12:34:53
 *
 */
public class AutoGetCaptcha {

	public static AutoGetCaptcha mAutoGetCaptcha;
	private Context mContext;
	public static Bitmap mBitmap;
	private int t = 0;// RGB值相同个数
	private int f = 0;// RGB值不相同个数

	public static AutoGetCaptcha getInstanse(Context context, Bitmap bitmap) {
		if (mAutoGetCaptcha == null) {
			mAutoGetCaptcha = new AutoGetCaptcha(context, bitmap);
		}
		AutoGetCaptcha.mBitmap=bitmap;
		return mAutoGetCaptcha;
	}

	public AutoGetCaptcha(Context context, Bitmap bitmap) {
		this.mBitmap = bitmap;
		this.mContext = context;
	};

	public void getCaptcha(IGetcaptchaListener getcaptchaListener){
		AutoGetCaptcha.getcaptchaListener=getcaptchaListener;
		ThreadPoolUtils.execute(new getCaptchaRunnable());
	}
	
	public static IGetcaptchaListener getcaptchaListener;
	public interface IGetcaptchaListener{
		void onComplete(String result);
		void onError(Exception e);
	}

	public String TAG="++";
	/**
	 * 获得验证码
	 */
	public class getCaptchaRunnable implements Runnable{
		@Override
		public void run() {
			long time=System.currentTimeMillis();
			String result="";
			try {
				List<Bitmap> listBitmap = splitImage(mBitmap);
				double max=0;
				int index=0;
				for (int j = 0; j < 4; j++) {
					double similarNum[] = new double[10];// 对比RGB的相似值
					Bitmap bitmap1 = convertToBlackWhite(listBitmap.get(j));
					for (int i = 0; i < 10; i++) {
						similarNum[i] = similarity(bitmap1, getCaptchaImg(i));
						t = 0;
						f = 0;
						if(similarNum[i]>max){
							max=similarNum[i];
							index=i;
						}
					}
					result+=index+"";
					index=0;
					max=0;
				}
			} catch (Exception e) {
				getcaptchaListener.onError(e);
			}
			Log.i(TAG,"识别验证码花费时间："+(System.currentTimeMillis()-time));
			Log.i(TAG, "验证码:     " + result.trim());
			mBitmap=null;
			getcaptchaListener.onComplete(result.trim());
		}
		
	}
	
	

	/**
	 * 分割图片
	 * 
	 * @param bitmap
	 * @return List<Bitmap>
	 * @throws Exception
	 */
	public List<Bitmap> splitImage(Bitmap bitmap) throws Exception {
		List<Bitmap> subImgs = new ArrayList<Bitmap>();
		for (int i = 6; i <= 42; i += 12) {
			Bitmap img = Bitmap.createBitmap(bitmap, i, 16, 8, 10);
			subImgs.add(img);
		}
		return subImgs;
	}

	/**
	 * 图片灰度处理
	 * 
	 * @param bmp
	 * @return
	 */
	public Bitmap convertToBlackWhite(Bitmap bmp) {
		int width = bmp.getWidth(); // 获取位图的宽
		int height = bmp.getHeight(); // 获取位图的高
		int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

		bmp.getPixels(pixels, 0, width, 0, 0, width, height);
		int alpha = 0xFF << 24;
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width; j++) {
				int grey = pixels[width * i + j];

				// 分离三原色
				int red = ((grey & 0x00FF0000) >> 16);
				int green = ((grey & 0x0000FF00) >> 8);
				int blue = (grey & 0x000000FF);

				// 转化成灰度像素
				grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
				grey = alpha | (grey << 16) | (grey << 8) | grey;
				pixels[width * i + j] = grey;
			}
		}
		// 新建图片
		Bitmap newBmp = Bitmap.createBitmap(width, height, Config.RGB_565);
		// 设置图片数据
		newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

		Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 380, 460);
		return resizeBmp;
	}

	/**
	 * 图片像素比较
	 * 
	 * @param bm_one
	 * @param bm_two
	 * @return double
	 */
	public double similarity(Bitmap bm_one, Bitmap bm_two) {
		// 把图片转换为Bitmap
		// Bitmap bm_one = BitmapFactory.decodeFile(url_one);
		// Bitmap bm_two = BitmapFactory.decodeFile(url_two);
		// 保存图片所有像素个数的数组，图片宽×高
		int[] pixels_one = new int[bm_one.getWidth() * bm_one.getHeight()];
		int[] pixels_two = new int[bm_two.getWidth() * bm_two.getHeight()];
		// 获取每个像素的RGB值
		bm_one.getPixels(pixels_one, 0, bm_one.getWidth(), 0, 0, bm_one.getWidth(), bm_one.getHeight());
		bm_two.getPixels(pixels_two, 0, bm_two.getWidth(), 0, 0, bm_two.getWidth(), bm_two.getHeight());

		// 如果图片一个像素大于图片2的像素，就用像素少的作为循环条件。避免报错
		if (pixels_one.length >= pixels_two.length) {
			// 对每一个像素的RGB值进行比较
			for (int i = 0; i < pixels_two.length; i++) {
				int clr_one = pixels_one[i];
				int clr_two = pixels_two[i];
				// RGB值一样就加一（以便算百分比）
				if (clr_one == clr_two) {
					t++;
				} else {
					f++;
				}
			}
		} else {
			for (int i = 0; i < pixels_one.length; i++) {
				int clr_one = pixels_one[i];
				int clr_two = pixels_two[i];
				if (clr_one == clr_two) {
					t++;
				} else {
					f++;
				}
			}

		}

		return myPercent(t, t + f);
	}

	/**
	 * 百分比的计算
	 * 
	 * @param y
	 * @param z
	 * @return Double
	 */
	public double myPercent(int y, int z) {
		String baifenbi = "";// 接受百分比的值
		double baiy = y * 1.0;
		double baiz = z * 1.0;
		double fen = baiy / baiz;
		DecimalFormat df1 = new DecimalFormat("0.0000"); // ##.00%
		baifenbi = df1.format(fen);
		return Double.valueOf(baifenbi).doubleValue();
	}

	/**
	 * 计算最大值的位置
	 * 
	 * @param arr
	 * @return int
	 */
	public int getMax(double[] arr) {
		int index = 0;
		double max;
		max = arr[0];
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > max) // 判断最大值
			{
				max = arr[i];
				index = i;
			}
		}
		return index;
	}

	/**
	 * 获取对比验证码图片资源
	 * 
	 * @param index
	 * @return Bitmap
	 */
	public Bitmap getCaptchaImg(int index) {
		Bitmap img = null;
		switch (index) {
		case 0:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_0);
			break;
		case 1:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_1);
			break;
		case 2:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_2);
			break;
		case 3:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_3);
			break;
		case 4:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_4);
			break;
		case 5:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_5);
			break;
		case 6:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_6);
			break;
		case 7:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_7);
			break;
		case 8:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_8);
			break;
		case 9:
			img = PicUtil.bitmap(mContext, R.drawable.captcha_9);
			break;
		default:

			break;
		}
		return img;
	}
}
